<template>
    <div class="addHouse">
        <div class="top">
            <!--下拉切换-->
            <div class="main" style="justify-content: space-between;flex-direction: inherit;width: 740px;">
                <CommonSelectRouter :dataList="addHouseRouter.data"
                    :default="this.$route.query.convert ? addHouseRouter.default + '(' + $t('text.House.l289') + ')' : addHouseRouter.default"
                    ref="child1" @returnData="getRouter" isLock>
                </CommonSelectRouter>
                <el-button type="primary" @click="handleClick" style="width: 85px;height: 30px;" :loading="loading">
                    {{ $t("text.House.l144") }}
                </el-button>
            </div>
        </div>
        <div class="main">
            <!--表单结构渲染-->
            <div v-if="isload">
                <div v-for="(s, index1) in addHousePage" v-bind:key="s.headTitle" style="width: 100%;">
                    <div class="headTitle">{{ s.headTitle }}</div>
                    <div class="df">
                        <div v-for="(item, index2) in s.data" v-bind:key="item.title"
                            :style="item.type == 'radio' || item.type == 'br' ? { paddingRight: '15px', width: '100%' } : { paddingRight: '15px' }">

                            <div class="title" v-if="item.type != 'br'"><span class="must" v-if="item.isMust">※</span>{{
                                item.title }}</div>
                            <CommonInputKey v-if="item.type == 'input'" :leftText="item.defaultUnit" :isMust="item.isMust"
                                :mustHit="item.mustHit" :insertKey="item.insertKey" @returnData="setData"
                                :isNumber="item.isNumber" :default="insertData[item.insertKey]" :min="item.min"
                                :ref="'child' + index1 + index2" :is-format="item.format">
                            </CommonInputKey>

                            <CommonInputAndSelect v-if="item.type == 'input2'" :leftText="item.defaultUnit"
                                :isMust="item.isMust" :mustHit="item.mustHit" :insertKey="item.insertKey" :hit="item.hit"
                                :dataList="community" @returnData="setData" :default="insertData.intentionCommunity"
                                :isNumber="item.isNumber" :ref="'child' + index1 + index2">
                            </CommonInputAndSelect>

                            <CommonSelectKey v-if="item.type == 'select'" :dataList="dictionaryTree[item.dictionaryKey]"
                                :isMust="item.isMust" :mustHit="item.mustHit" :insertKey="item.insertKey"
                                @returnData="setData" :ref="'child' + index1 + index2"
                                :default="isEdit ? insertData[item.insertKey] == null || insertData[item.insertKey] == '' ? item.default : getSelectDefault(item.insertKey) : item.default"
                                :isSelect="insertData[item.insertKey] == null ? false : isEdit">
                            </CommonSelectKey>

                            <CommonRadioKey v-if="item.type == 'radio'" :dataList="dictionaryTree[item.dictionaryKey]"
                                :isMust="item.isMust" :mustHit="item.mustHit" :insertKey="item.insertKey"
                                @returnData="setData" :ref="'child' + index1 + index2"
                                :isValue="item.dictionaryKey == 'roomType' ? true : false"
                                :default="insertData[item.insertKey] == null ? [] : getRadioDict(insertData[item.insertKey].split(','), item.dictionaryKey)">
                            </CommonRadioKey>

                            <RadioSelect v-if="item.type == 'radioSelect'" :selectList="areaList" @returnData="setData"
                                :searchKey="item.insertKey" retuenAll :fastSearch="insertData.area" :showStyle="{
                                    fontSize: '12px', height: '22px', border: '1px solid rgb(238, 238, 238)', borderRadius: '4px',
                                    width: '158px', textAlign: 'center', display: 'flex', alignItems: 'center', justifyContent: 'center'
                                }" isArea isShowTitle isShowSerach1 >
                            </RadioSelect>

                            <CommonRangeInput v-if="item.type == 'rangeInput'"
                                :dataList="dictionaryTree[item.dictionaryKey]" :isMust="item.isMust" :mustHit="item.mustHit"
                                :insertKey="item.insertKey" @returnData="setData"
                                :default1="insertData[item.insertKey.split(',')[0]]" :max="item.max"
                                :default2="insertData[item.insertKey.split(',')[1]]" :ref="'child' + index1 + index2">
                            </CommonRangeInput>

                            <CommonTextarea v-if="item.type == 'textarea'" :defaults="item.default"
                                :insertKey="item.insertKey" @returnData="setData" class="main"
                                :value="insertData[item.insertKey]" :maxlength="100">
                            </CommonTextarea>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>
    
<script>
import { ElMessage } from 'element-plus'
import { addCustomPage1, addCustomPage2 } from '../../itemList';
import { getInsertDropdownData2, customerInsert, communityFindAll, areaFindTreeAll, customerUpdate, changeRentBuy } from '../../http/api'
import CommonSelectRouter from '../../components/input/CommonSelectRouter.vue';
import CommonInputKey from '../../components/input/CommonInputKey.vue';
import CommonInputAndSelect from '../../components/input/CommonInputAndSelect.vue';
import CommonSelectKey from '../../components/input/CommonSelectKey.vue';
import CommonRadioKey from '../../components/input/CommonRadioKey.vue';
import CommonRangeInput from '../../components/input/CommonRangeInput.vue';
import CommonTextarea from '../../components/input/CommonTextarea.vue';
import RadioSelect from '../../components/select/RadioSelect.vue';

export default {
    name: 'AddCustom',
    components: {
        CommonSelectRouter: CommonSelectRouter,
        CommonInputKey: CommonInputKey,
        CommonInputAndSelect: CommonInputAndSelect,
        CommonSelectKey: CommonSelectKey,
        CommonRadioKey: CommonRadioKey,
        CommonRangeInput: CommonRangeInput,
        CommonTextarea: CommonTextarea,
        RadioSelect: RadioSelect
    },
    data() {
        return {
            addHouseRouter: {
                default: this.$t("text.House.l145"),
                data: [
                    { id: 1, name: this.$t("text.House.l145") },
                    { id: 2, name: this.$t("text.House.l146") },
                ]
            },
            addHouseRouter2: {
                data: [
                    { id: 1, name: this.$t("text.Common.l55") },
                    { id: 2, name: this.$t("text.Common.l56") },
                ]
            },
            addHousePage: addCustomPage1,
            dictionaryTree: {},
            isload: false,
            insertData: { customerClass: 0 },
            community: [],
            communityCopy: [],
            areaList: [],
            isEdit: false,
            loading: false,
            dictConver: ['houseType'],
        }
    },
    mounted() {

        if (this.$route.query.index != undefined) {
            this.getRouter(Number(this.$route.query.index) + 1)
            this.addHouseRouter.default = this.addHouseRouter.data.find(v => v.id === Number(this.$route.query.index) + 1)?.name || '';
        }

        if (this.$route.query.edit == 'true' && localStorage.getItem("addCustom") != null) {
            this.isEdit = true
            this.getRouter(Number(this.$route.query.index) + 1)
            this.addHouseRouter.default = this.addHouseRouter2.data.find(v => v.id === Number(this.$route.query.index) + 1)?.name || '';
            this.insertData = { customerClass: this.$route.query.index, ...JSON.parse(localStorage.getItem("addCustom")) }
        }

        getInsertDropdownData2().then(res => {
            if (res !== undefined) {
                this.dictionaryTree = res
                if (res.customerType) {
                    res.customerType.length = 3
                }
                communityFindAll().then(res => {
                    this.community = res
                    this.communityCopy = JSON.parse(JSON.stringify(res))
                }).catch()

                areaFindTreeAll().then(res => {
                    if (res !== undefined) {
                        this.areaList =  [{ dictName: this.$t('text.Common.l12'), id: null }, ...res]
                        this.isload = true
                    }
                }).catch()

            }
        }).catch()

    },
    methods: {
        //编辑时获取下拉框默认填充值
        getSelectDefault(key) {
            let findContain = this.dictConver.filter(v => v === key)
            if (findContain.length > 0) {
                //需要进行转换
                let defaultName = this.dictionaryTree[key].filter(v => v.dictValue === this.insertData[key])
                if (defaultName.length <= 0) return ''
                return defaultName[0].dictName
            } else {
                //不需要转换直接返回
                return this.insertData[key]
            }
        },

        handleClick() {
            let flag = true
            this.addHousePage.forEach((element, index1) => {
                element.data.forEach((item, index2) => {
                    const childRef = this.$refs['child' + index1 + index2]
                    if (childRef && childRef.length > 0 && !childRef[0].inputReturn()) {
                        flag = flag && false
                    }
                });
            });
            if (flag) {
                this.insert()
            } else {
                ElMessage.error({
                    showClose: true,
                    message: this.$t('text.Common.l999'),
                    type: 'error',
                })
            }
        },

        //切换
        getRouter(index) {
            switch (index) {
                case 1: this.addHousePage = addCustomPage1; this.insertData = { customerClass: 0 }; break;
                case 2: this.addHousePage = addCustomPage2; this.insertData = { customerClass: 1 }; break;
                // case 3: this.addHousePage = addCustomPage2; this.insertData = { customerClass: 2 }; break;
            }
        },

        //多选框值转换
        getRadioDict(list, key) {
            let dict = []
            let data
            list.forEach(element => {
                data = this.dictionaryTree[key].filter(v => v.dictValue === element)
                if (data.length > 0) {
                    dict = [...dict, this.dictionaryTree[key].filter(v => v.dictValue === element)[0].dictName]
                }
            });
            return dict
        },

        //提交上传
        insert() {
            this.loading = true
            if (this.isEdit) {
                if (this.$route.query.convert) {
                    changeRentBuy({ id: this.$route.query.id, newStatus: this.$route.query.newStatus, oldStatus: this.$route.query.oldStatus, }).then(res => {
                        if (res !== undefined) {
                            setTimeout(() => {
                                customerUpdate(this.insertData).then(res => {
                                    this.loading = false
                                    if (res !== undefined) {
                                        ElMessage.success({
                                            showClose: true,
                                            message: this.$t('text.Common.l3'),
                                            type: 'success',
                                        })
                                        this.$router.back()
                                    }
                                }).catch()
                            }, 1100)
                        } else {
                            this.loading = false
                        }
                    }).catch()
                    return;
                }
                customerUpdate(this.insertData).then(res => {
                    this.loading = false
                    if (res !== undefined) {
                        ElMessage.success({
                            showClose: true,
                            message: this.$t('text.Common.l3'),
                            type: 'success',
                        })
                        this.$router.back()
                    }
                }).catch()
            } else {
                customerInsert(this.insertData).then(res => {
                    this.loading = false
                    if (res !== undefined) {
                        ElMessage.success({
                            showClose: true,
                            message: this.$t('text.Customer.l1'),
                            type: 'success',
                        })
                        this.$router.back()
                    }
                }).catch()
            }
        },
        //接收返回值
        setData(obj) {
            if (Object.keys(obj).includes("myAreaIds")) {
                this.community = this.communityCopy.filter(v => v.areaIds.includes(obj.myAreaIds.id))
                this.insertData.intentionCommunity = ''
                obj.areaName = obj.myAreaIds.areaName
                obj.areaIds = obj.myAreaIds.id
            }
            this.insertData = { ...this.insertData, ...obj }
        }
    },
    watch: {
    },
    computed: {

    }

}
</script>
    
<style scoped>
.addHouse {
    width: 100%;
}

.main {
    /* width: 100%; */
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 700px;
    margin: 0 auto;
}


.df {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    border-bottom: 1px solid rgb(220, 223, 230);
    padding-bottom: 25px;
}

.title {
    font-size: 12px;
    color: black;
    text-align: left;
    display: flex;
    align-items: center;
    padding-top: 15px;
    padding-bottom: 5px;
    font-weight: 600;
}

.top {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
    border-bottom: 1px solid rgb(220, 223, 230);
    padding-top: 7px;
    padding-bottom: 7px;
    position: sticky;
    top: 29px;
    background: white;
    z-index: 53;
    box-shadow: 1px 1px 10px 5px #f8f8f8
}

.headTitle {
    font-size: 14px;
    color: #aaa;
    text-align: left;
    padding-top: 20px
}

.must {
    font-size: 12px;
    color: red;
    padding-right: 5px;
}
</style>